<template>
  <el-tabs v-model="activeTab" type="card" @click="handleTabClick">
    <el-tab-pane label="我学习的课程" name="courses">
      <div v-if="activeTab === 'courses'">
        <!-- 课程分类 -->
        <div class="category-list">
        <span
            v-for="courseType in courseTypeList"
            :key="courseType.code"
            :class="['category-item', { active: selectedCode === courseType.code }]"
            @click="selectCategory(courseType.code)"
        >
          {{ courseType.name }}
        </span>
        </div>
        <el-row :gutter="20" class="course-list">
          <el-col
              v-for="course in tableData"
              :key="course.courseId"
              :span="6"
              class="course-item"
              @click="courseDetail(course.courseId)"
          >
            <el-card>
              <img :src="course.courseImage" alt="课程图片" class="course-image" />
              <div class="course-name">{{ course.courseName }}</div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <el-pagination style="margin-top:20px"
                       :current-page="searchForm.pageNum"
                       :page-size="searchForm.pageSize"
                       :page-sizes="[8,12]" layout="->,total, sizes, prev, pager, next, jumper"
                       :total="total"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-tab-pane>
    <el-tab-pane label="我发布的贴子" name="comments">
      <div v-if="activeTab === 'comments'">
        <el-header>
        <div class="header-content">
          <el-input
              v-model="commentSearchForm.title"
              placeholder="搜索标题或者内容"
              class="search-input"
          />
          <el-button type="primary" @click="searchTalk">搜索</el-button>
          <el-button @click="resetCourse">重置</el-button>
        </div>
        </el-header>
        <div class="post-list">
          <!-- 遍历当前页的帖子 -->
          <div v-for="(post, index) in commentData" :key="post.id" @click="talkDetailClick(post.id)" class="post-item">
            <!-- 帖子标题 -->
            <h2 class="post-title">{{ post.title }}</h2>
            <div class="container">
              <!-- 图片展示在左边 -->
              <img v-if="post.imageUrl" :src="post.imageUrl" alt="图片" class="image" />
              <!-- 文字展示在右边 -->
              <div class="text" v-html="post.truncatedText"></div>
            </div>
            <!-- 分割线 -->
            <el-divider v-if="index < commentData.length - 1" />
          </div>
        </div>

        <!-- 分页 -->
        <el-pagination style="margin-top:20px"
                       :current-page="commentSearchForm.pageNum"
                       :page-size="commentSearchForm.pageSize"
                       :page-sizes="[2,4,6,8]" layout="->,total, sizes, prev, pager, next, jumper"
                       :total="commentTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-tab-pane>
    <el-tab-pane label="我发布的评论" name="myComment">
      <div v-if="activeTab === 'myComment'">
        <el-header>
          <div class="header-content">
            <el-input
                v-model="commentSearchForm.title"
                placeholder="搜索标题或者内容"
                class="search-input"
            />
            <el-button type="primary" @click="searchTalkComment">搜索</el-button>
            <el-button @click="resetCourseComment">重置</el-button>
          </div>
        </el-header>
        <div class="post-list">
          <!-- 遍历当前页的帖子 -->
          <div v-for="(post, index) in myCommentData" :key="post.id" @click="talkDetailClick(post.id)" class="post-item">
            <!-- 帖子标题 -->
            <h2 class="post-title">{{ post.title }}</h2>
            <div class="container">
              <!-- 图片展示在左边 -->
              <img v-if="post.imageUrl" :src="post.imageUrl" alt="图片" class="image" />
              <!-- 文字展示在右边 -->
              <div class="text" v-html="post.truncatedText"></div>
            </div>
            <!-- 分割线 -->
            <el-divider v-if="index < myCommentData.length - 1" />
          </div>
        </div>

        <!-- 分页 -->
        <el-pagination style="margin-top:20px"
                       :current-page="commentSearchForm.pageNum"
                       :page-size="commentSearchForm.pageSize"
                       :page-sizes="[2,4,6,8]" layout="->,total, sizes, prev, pager, next, jumper"
                       :total="myCommentTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-tab-pane>
  </el-tabs>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import { useRouter } from 'vue-router';
import dictAPI from "@/api/module/dict";
import courseAPI from "@/api/module/myCourse";
import talkAPI from "@/api/module/talk";

// 搜索条件
const searchForm = reactive({
  courseName:'',
  courseType:'',
  pageNum: 1,
  pageSize: 8,
})
//我发布的贴子-搜索条件
const commentSearchForm = reactive({
  title:'',
  pageNum: 1,
  pageSize: 2,
})

// 课程数据
let tableData = ref([]);
const activeTab = ref('courses');
let selectedCode = ref(null);
let courseTypeList = ref([]);
let total = ref(0);
const newItem = { code: 'all', name: '全部' };

//发布的评论数据
let commentData = ref([]);
let commentTotal = ref(0);
//我评论的帖子
let myCommentData = ref([]);
let myCommentTotal = ref(0);

// Dom 挂载之后
onMounted(() => {
  typeList();
  switchToFirstTab();
  getCourseList();
  getTalkList();
  getCommentList();
})

//获取课程类型字典值下拉框
const typeList = async () => {
  const res = await dictAPI.list('COURSE_TYPE');
  courseTypeList.value = JSON.parse(res.data[0].dictionaryValue);
  courseTypeList.value.unshift(newItem);
}

// 选择分类
const selectCategory = (code) => {
  searchForm.courseType = code;
  selectedCode.value = code;
  getCourseList();
};


//根据code过滤课程
const getCourseList = async () => {
  if(searchForm.courseType === 'all'){
    searchForm.courseType = null;
  }
  const res = await courseAPI.page(searchForm);
  tableData.value = res.data.records;
  total.value = res.data.total;
}
const handleSizeChange = (size) => {
  if(searchForm.courseType === 'all'){
    searchForm.courseType = null;
  }
  searchForm.pageSize = size;
  getCourseList();
}
const handleCurrentChange = (current) => {
  if(searchForm.courseType === 'all'){
    searchForm.courseType = null;
  }
  searchForm.pageNum = current;
  getCourseList();
}

// 切换到第一个 tab 的方法
const switchToFirstTab = () => {
  selectedCode.value = 'all'; // 将 activeTab 设置为第一个 tab 的值
};

const router = useRouter();

//跳转到课程详情页面
const courseDetail =  (courseId) => {
  router.push({
    path:'/detail/' + Date.now(),
    query:{
      "courseId": courseId
    }
  });
}

//查询
const searchTalk = () => {
  commentSearchForm.pageNum = 1;
  getTalkList();
}
//重置
const resetCourse = () => {
  commentSearchForm.title = '';
  commentSearchForm.current = 1;
  getTalkList();
}
//我发布的评论-根据title过滤课程
const getTalkList = async () => {
  const res = await talkAPI.myTalk(commentSearchForm);
  commentData.value = res.data.records;
  commentTotal.value = res.data.total;
  commentData.value.forEach((content) => {
    // 提取第一张图片的 URL
    const contentNew = content.content || ''; // 确保 content 是字符串
    const imgRegex = /<img[^>]+src="([^">]+)"/;
    const match = contentNew.match(imgRegex);
    const imageUrl = match ? match[1] : '';
    // 去除图片标签，保留纯文本
    const textWithoutImages = contentNew.replace(/<img[^>]*>/g, '');
    // 保留 3 行文字
    const lines = textWithoutImages.split('</p>').slice(0, 3);
    const truncatedText = lines.join('</p>') + (lines.length < 3 ? '' : '...');
    content.imageUrl = imageUrl;
    content.truncatedText = truncatedText;
  })
}

//跳转详情页面
const talkDetailClick =  (id) => {
  router.push({
    path:'/talkDetail/' + Date.now(),
    query:{
      "id": id
    }
  });
}

//我评论的帖子-根据title过滤课程
const getCommentList = async () => {
  const res = await talkAPI.myComment(commentSearchForm);
  myCommentData.value = res.data.records;
  myCommentTotal.value = res.data.total;
  myCommentData.value.forEach((content) => {
    // 提取第一张图片的 URL
    const contentNew = content.content || ''; // 确保 content 是字符串
    const imgRegex = /<img[^>]+src="([^">]+)"/;
    const match = contentNew.match(imgRegex);
    const imageUrl = match ? match[1] : '';
    // 去除图片标签，保留纯文本
    const textWithoutImages = contentNew.replace(/<img[^>]*>/g, '');
    // 保留 3 行文字
    const lines = textWithoutImages.split('</p>').slice(0, 3);
    const truncatedText = lines.join('</p>') + (lines.length < 3 ? '' : '...');
    content.imageUrl = imageUrl;
    content.truncatedText = truncatedText;
  })
}

//查询
const searchTalkComment = () => {
  commentSearchForm.pageNum = 1;
  getCommentList();
}
//重置
const resetCourseComment = () => {
  commentSearchForm.title = '';
  commentSearchForm.current = 1;
  getCommentList();
}
</script>

<style scoped>
.category-list {
  margin-bottom: 20px;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.category-item {
  margin-right: 20px;
  font-size: 16px;
  cursor: pointer;
  color: #666;
  transition: color 0.3s;
}


.category-item:hover {
  color: #409eff;
}

.category-item.active {
  color: #409eff;
  font-weight: bold;
  //background-color: #409eff;
  //color: white;
}

.course-list {
  margin-top: 20px;
}

.course-item {
  margin-bottom: 20px;
}

.course-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.course-name {
  margin-top: 10px;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
}

/* 我发布的评论*/
.search-input {/* 页面导航栏 */
  width: 1000px;
  margin-right: 20px;
}

.post-list {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.post-item {
  margin-bottom: 20px;
}

.post-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #1a1a1a;
}

/* 容器布局 */
.container {
  display: flex;
  align-items: flex-start;
  gap: 16px; /* 图片和文字之间的间距 */
}

/* 图片样式 */
.image {
  width: 150px; /* 图片宽度 */
  height: 150px; /* 高度自适应 */
  border-radius: 8px; /* 圆角 */
}

/* 文字样式 */
.text {
  flex: 1; /* 占据剩余空间 */
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制为 3 行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>